//
//  ComposeViewContorller.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/5/9.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewContorller: UIViewController
{
    /// 工具条底部约束
    var toolbarBottonCons: NSLayoutConstraint?
    /// 图片选择器高度约束
    var photoViewHeightCons: NSLayoutConstraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        // 注册通知，监听键盘弹出和消失
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewContorller.keyboardChange(_:)), name: "UIKeyboardWillChangeFrameNotification", object: nil)
        
        // 将 键盘控制器 和 图片选择器 添加为当前控制器为子控制器
        addChildViewController(emoticonVC)
        addChildViewController(photoSelectorVC)
        
        // 初始化导航条
        setupNav()
        
        // 初始化输入框
        setupTextView()
        
        // 初始化图片选择器
        setupPhotoSelectorVC()
        
        // 初始化工具条
        setupToolBar()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if photoViewHeightCons?.constant == 0
        {
            // 主动显示键盘
            textView.becomeFirstResponder()
        }
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    /**
     析构方法
     */
    deinit
    {
        // 注销监听
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    /**
     监听键盘改变，调用方法
     */
    func keyboardChange(notify: NSNotification)
    {
        // 取出键盘最终rect
        let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let rect = value.CGRectValue()
        
        // 调整toolbar的底部约束 = 屏幕高度 - 键盘高度
        toolbarBottonCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        // 更新界面
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        
        /*
         工具条回弹是因为执行了两次动画, 而系统自带的键盘的动画节奏(曲线) 7
         7在apple API中并没有提供给我们, 但是我们可以使用
         7这种节奏有一个特点: 如果连续执行两次动画, 不管上一次有没有执行完毕, 都会立刻执行下一次
         也就是说上一次可能会被忽略
         
         如果将动画节奏设置为7, 那么动画的时长无论如何都会自动修改为0.5
         
         UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏
         */
        
        // 取出键盘动画节奏（曲线）
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSInteger
    
        // 使用动画变更toolbar的位置，同事设置与键盘相同的动画节奏
        UIView.animateWithDuration(duration.doubleValue) {
            // 设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    /**
     初始化输入框
     */
    private func setupTextView()
    {
        // 添加控件
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        
        // 布局控件
        textView.xmg_Fill(view)
        placeholderLabel.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
    }
    
    /**
     选择相片
     */
    func selectPicture()
    {
        // 1.关闭键盘
        textView.resignFirstResponder()
        
        // 2.调整图片选择器的高度
        photoViewHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
    }
    
    /**
     初始化导航条
     */
    private func setupNav()
    {
        // 添加左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewContorller.close))
        
        // 添加右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewContorller.sendStatus))
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        // 添加中间视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        let l1 = UILabel()
        l1.font = UIFont.systemFontOfSize(15)
        l1.text = "发送微博"
        l1.sizeToFit()
        titleView.addSubview(l1)
        
        let l2 = UILabel()
        l2.font = UIFont.systemFontOfSize(13)
        l2.textColor = UIColor.darkGrayColor()
        l2.text = UserAccount.loadAccount()?.screen_name
        l2.sizeToFit()
        titleView.addSubview(l2)
        
        // 布局
        l1.xmg_AlignInner(type: XMG_AlignType.TopCenter, referView: titleView, size: nil)
        l2.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    /**
     初始化图片选择器
     */
    func setupPhotoSelectorVC()
    {
        // 添加图片选择器
        view.insertSubview(photoSelectorVC.view, belowSubview: toolBar)
        
        // 布局
        let size = UIScreen.mainScreen().bounds.size
        let width = size.width
        let height: CGFloat = 0
        let cons = photoSelectorVC.view.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: height))
        photoViewHeightCons = photoSelectorVC.view.xmg_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    /**
     初始化工具栏
     */
    private func setupToolBar()
    {
        // 添加子控件
        view.addSubview(toolBar)
        view.addSubview(tipLabel)
        
        // 添加按钮
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
                            
                            ["imageName": "compose_mentionbutton_background"],
                            
                            ["imageName": "compose_trendbutton_background"],
                            
                            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
                            
                            ["imageName": "compose_addbutton_background"]]
        for dict in itemSettings
        {
            
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"])
            items.append(item)
            // 添加按钮间隔
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后一个间隔（FlexibleSpace）
        items.removeLast()
        toolBar.items = items
        
        // 布局toolbar
        let width = UIScreen.mainScreen().bounds.width
        let cons = toolBar.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: 44))
        toolbarBottonCons = toolBar.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        toolBar.items = items
        
        // 布局tipLabel
        tipLabel.xmg_AlignVertical(type: XMG_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -10, y: -10))
    }
    
    /**
     切换表情键盘
     */
    func inputEmoticon()
    {
        // 如果第一次是系统自带的键盘inputView为nil
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 将表情键盘的控制器的view设置为UItextView的inputView
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
        // 重新唤出键盘
        textView.becomeFirstResponder()
    }
    
    /**
     发送文本微博
     */
    func sendStatus()
    {
        // 准备发送内容
        let text = textView.emoticonAttributedText()
        let image = photoSelectorVC.pictureImages.first
        
        NetworkTools.shareNetworkTools().sendStatus(text, image: image, successCallback: { (status) in
            // 提示发送成功
            SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
            // 关闭发送界面
            self.close()
            }) { (error) in
                // 提示发送失败
                SVProgressHUD.showInfoWithStatus("发送失败", maskType: SVProgressHUDMaskType.Black)
        }
    }
    
    /**
     关闭按钮
     */
    func close()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 懒加载
    /// 文本输入框
    private lazy var textView: UITextView = {
       let t = UITextView()
        t.delegate = self
        t.font = UIFont.systemFontOfSize(20)
        t.alwaysBounceVertical = true
        t.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return t
    }()
    
    /// 水印文字
    private lazy var placeholderLabel: UILabel = {
       let l = UILabel()
        l.text = "分享新鲜事..."
        l.font = UIFont.systemFontOfSize(20)
        l.textColor = UIColor.darkGrayColor()
        return l
    }()
    
    // swift中使用闭包如同block，使用self时也需要弱引用，不然会循环引用，[weak self]、[unowned self]
    // [weak self] 相当于OC中 __weak，对象释放之后会将变量设置为nil
    // [unowned self] 相当于OC中 unsafe_unretained,对象释放后不会将变量设置为nil
    /// 表情键盘
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController {[weak self] (emoticon) in
        self!.textView.insertEmoticon(emoticon)
    }
    
    /// 图片选择器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    
    /// 底部工具栏
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    private lazy var tipLabel: UILabel = {
       let l = UILabel()
        l.textColor = UIColor.darkGrayColor()
        l.font = UIFont.systemFontOfSize(15)
        return l
    }()
}

private let maxTipTextLength = 140
extension ComposeViewContorller: UITextViewDelegate
{
    func textViewDidChange(textView: UITextView)
    {
        // 隐藏水印文字
        placeholderLabel.hidden = textView.hasText()
        // 判断输入内容是否为空，控制是否可以发微博
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        // 改变已输入字数
        let count = textView.emoticonAttributedText().characters.count
        // 可输入差值
        let dif = maxTipTextLength - count
        tipLabel.textColor = (dif) > 0 ? UIColor.darkGrayColor() : UIColor.redColor()
        tipLabel.text = (dif < 10) ? "\(dif)" : ""
    }
    
    private func text()
    {
        do{
            let data = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue))
        }catch
        {
            
        }
    }
}
